package linc.cool.application;

import linc.cool.factory.UnsafeFactory;
import lombok.extern.slf4j.Slf4j;

/**
 * @author yqlin
 * @date 2021/12/12 10:28 PM
 * @description 锁类实例对象
 */
@Slf4j
public class SyncLockInstantiationObjDemo {

    private static int counter = 0;

    private static String lock = "";

    public static void increment() {
        synchronized (lock) {
            UnsafeFactory.getUnsafe().monitorEnter(lock);
            try {
                counter++;
            } finally {
                UnsafeFactory.getUnsafe().monitorExit(lock);
            }
        }
    }

    public static void decrement() {
        synchronized (lock) {
            counter--;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                increment();
            }
        }, "t1");
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                decrement();
            }
        }, "t2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();


        log.info("counter={}", counter);
    }
}
